import pickle
import pkuseg
import gensim
import re
import openpyxl
import numpy as np
import torch.nn as nn
import torch
import module
import csv
import torch.optim as optim
from torch.autograd import Variable

excel_file="C://Users//滑稽鸭阁//Documents//Tencent Files//1160636624//FileRecv//ad表格.xlsx"
wb = openpyxl.load_workbook(excel_file)
sh= wb['工作表1']

seg = pkuseg.pkuseg(model_name='default',user_dict = "D://皮炎参数//分词汇总.txt")

dict_chengdu = dict()
dict_mi = dict()
dict_yuansu=dict()

with open('D://皮炎参数//分泌物培养结果_程度.txt',encoding='utf-8') as f:
    lines = f.readlines()
f.close()
size=0
strs=''
for ch in range(0,len(lines)-1,2):
    strs = lines[ch].strip('\n')
    size=lines[ch+1].strip('\n')
    dict_chengdu[str(strs)]=int(size)
print(dict_chengdu)

#np.save('D://data//dict_chengdu.npy',dict_chengdu)


with open('D://皮炎参数//元素汇总.txt',encoding='utf-8') as f:
    lines = f.readlines()
f.close()
size=0
for line in lines:
    line = line.strip('\n')
    dict_yuansu[str(line)]=size
    size=size+1
print(dict_yuansu)

#np.save('D://data//dict_yuansu.npy',dict_yuansu)

with open('D://皮炎参数//分泌物培养结果_物质.txt',encoding='utf-8') as f:
    lines = f.readlines()
f.close()
size=0
for line in lines:
    line = line.strip('\n')
    dict_mi[str(line)]=size
    size=size+1
print(dict_mi)
#np.save('D://data//dict_mi.npy',dict_mi)

stop=[]
with open('D://皮炎参数//停用词汇总.txt',encoding='utf-8') as f:
    lines = f.readlines()
    for line in lines:
        line = line.strip('\n')
        print(str(line))
        stop.append(str(line))
#np.save('D://data//stop.npy',stop )



datas=[]
for i in range(2,202):
    b=[0]*121
    blood= str(sh.cell(i,23).value)
    bic=str(sh.cell(i,24).value)
    sht=str(sh.cell(i,25).value)
    sht=sht.replace('阳性',' 1 ')
    sht=sht.replace('阴性',' 0 ')
    nblood=str(sh.cell(i,26).value)
    ige=str(sh.cell(i,27).value)
    mi=str(sh.cell(i,28).value)

    s=blood+' '+bic+' '+sht+' '+nblood+' '+ige+' '+mi




    for l in stop: 
        s=s.replace(l,' ')
    print(s)
    text=seg.cut(s)
    text.append('。')
    for ch in range(0,len(text)):
        if text[ch] in dict_mi.keys():
            if text[ch-1] in dict_chengdu.keys():
                b[dict_yuansu[text[ch]]]=float(dict_chengdu[text[ch-1]])
            elif text[ch+1] in dict_chengdu.keys():
                b[dict_yuansu[text[ch]]]=float(dict_chengdu[text[ch+1]])
            elif re.search(r'\d', text[ch+1] ):
                b[dict_yuansu[text[ch]]]=float(text[ch+1])
            else :
                b[dict_yuansu[text[ch]]]=float(3)
        elif text[ch] in dict_yuansu.keys():
            if re.search(r'\d', text[ch+1] ):
                b[dict_yuansu[text[ch]]]=float(text[ch+1])
            else :b[dict_yuansu[text[ch]]]=float(1)
    temp=np.array(b).reshape(11,11)
    print(temp)
    datas.append(temp)



net=module.CNN()
criterion = nn.MSELoss()
optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9)


labels=[]
way = dict()
excel_file="D://药剂.xlsx"
wb = openpyxl.load_workbook(excel_file)
sh= wb['工作表1']

with open('D://皮炎参数//way.txt') as f:
    lines = f.readlines()
f.close()

ways=[]
size=0
for line in lines:
    line = line.strip('\n')
    way[str(line)]=size
    ways.append(str(line))
    size=size+1
print(ways)
b=[0]*213
for i in range(2,202):
    b=[0]*213
    s= str(sh.cell(i,21).value)
    for l in ways:
        if s.find(l)!= -1:
            b[way[l]]=float(1)
    print(b)
    labels.append(b)



for epoch in range(12000):
    running_loss = 0.0
    for i,_ in enumerate(labels):
        label=labels[i]
        inputs=datas[i]
        inputs=np.array(inputs)
        inputs=inputs[np.newaxis,np.newaxis,:,:]
        label_num=[]
        label_num.append(label)
        label=torch.tensor(label_num, dtype=torch.long)
        inputs=torch.tensor(inputs ,dtype=torch.float32)
        inputs, label = Variable(inputs), Variable(label)
        optimizer.zero_grad()
        outputs = net(inputs)
        loss = criterion(outputs, label.float())
        loss.backward()
        optimizer.step()
        running_loss += loss.item()
        print('[%d, %5d] loss: %.3f' %
              (epoch + 1, i + 1, running_loss))
        running_loss = 0.0

torch.save(net, 'D:/model_finals2.pkl')
